package org.example.apitest.processfunction;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.example.apitest.beans.SensorReading;

public class ProcessTest2ApplicationCase {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // 从socket中读取数据
        DataStream<String> inputStream = env.socketTextStream("localhost", 7777);

        // 转换为SensorReading类型
        DataStream<SensorReading> dataStream = inputStream
                .map((MapFunction<String, SensorReading>) SensorReading::new);


        dataStream.keyBy("id")
                .process(new TempConsIncreWarning(10))
                .print();
        env.execute();
    }

    // 实现自定义处理函数,检测一段时间内的温度连续上升,输出报警
    public static class TempConsIncreWarning extends KeyedProcessFunction<Tuple, SensorReading, String> {
        // 定义私有属性,当前统计时间间隔
        private Integer interval;
        // 定义状态,保存上一次的温度值,定时器时间戳
        private ValueState<Double> lastTempState;
        private ValueState<Long> timerState;

        public TempConsIncreWarning(Integer interval) {
            this.interval = interval;
        }

        @Override
        public void open(Configuration parameters) throws Exception {
            super.open(parameters);
            lastTempState = getRuntimeContext().getState(new ValueStateDescriptor<>("last-temp", Double.class));
            timerState = getRuntimeContext().getState(new ValueStateDescriptor<>("timer-ts", Long.class));
            if (lastTempState.value() == null) {
                lastTempState.update(Double.MIN_VALUE);
            }
        }

        @Override
        public void close() throws Exception {
            super.close();
            lastTempState.clear();
            timerState.clear();
        }

        @Override
        public void processElement(SensorReading value, KeyedProcessFunction<Tuple, SensorReading, String>.Context ctx, Collector<String> out) throws Exception {
            // 取出状态
            Double lastTemp= lastTempState.value();
            Long timerTs=timerState.value();

            // 如果温度上升并且没有定时器,就要注册10秒后的定时器,开始等待
            if(value.getTemperature()>lastTemp && timerTs==null){
                // 计算出定时器时间戳
                Long ts= ctx.timerService().currentProcessingTime()+interval*1000L;
                ctx.timerService().registerProcessingTimeTimer(ts);
                timerState.update(ts);
            }else if(value.getTemperature()<=lastTemp && timerTs!=null){
                // 如果温度下降,删除定时器
                ctx.timerService().deleteProcessingTimeTimer(timerTs);
                timerState.clear();
            }

            // 更新温度状态
            lastTempState.update(value.getTemperature());
        }

        @Override
        public void onTimer(long timestamp, KeyedProcessFunction<Tuple, SensorReading, String>.OnTimerContext ctx, Collector<String> out) throws Exception {
            super.onTimer(timestamp, ctx, out);
            // 定时器触发,输出报警信息
            out.collect("传感器"+ctx.getCurrentKey().getField(0)+"温度值连续"+interval+"秒上升");
        }
    }
}
